package com.xmb.quick.exception;
 
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.xmb.quick.constant.R;

import lombok.extern.slf4j.Slf4j;


 
@ControllerAdvice
@Slf4j
public class ErrorExceptionHandler implements ErrorViewResolver {
 
	static final String PAGE_500 = "error/500";
    static final String PAGE_404 = "error/404";
    static final String PAGE_403 = "error/403";
    static final String OTHER_ERROR = "error/error";
    
    public static final String UNAUTHORIZED_VIEW = "error/unauthorized";
    
    @Autowired
    private HttpServletResponse response;
    
 
//    public String getTrace(Throwable t) {
//        StringWriter stringWriter= new StringWriter();
//        PrintWriter writer= new PrintWriter(stringWriter);
//        t.printStackTrace(writer);
//        StringBuffer buffer= stringWriter.getBuffer();
//        //String[] str = buffer.toString().split("\\r\\n\\t");
//        //buffer = new StringBuffer();
//        //Arrays.asList(str).forEach(buffer::append);
//        //buffer.append("Exception\r\n\t").append(str[0]).append("\r\n\t").append(str[1]);
//        writer.close();
//        return buffer.toString();
//    }

	@Override
	public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
        ModelAndView andView = new ModelAndView();
        
        andView.addObject("message", model.get("message"));
    	andView.addObject("url", model.get("path"));
    	
    	log.error(model.get("path")+"---发生异常---"+model.get("message"));
    	log.error(model.get("trace")+"");
		log.error("-----------------------------------------------------");
    	
    	
        if (404  == status.value()) {
            andView.setViewName(PAGE_404);
        } else if (403 == status.value()) {
            andView.setViewName(PAGE_403);
        } else if (status.is5xxServerError()) {
        	//如果是ajax请求响应头会有x-requested-with  
            if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){ 
            	response.setContentType("application/json;charset=UTF-8");
                PrintWriter writer = null;
				try {
					writer = response.getWriter();
					writer.write(JSON.toJSONString(R.error()));
					writer.flush();
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
            	return null;
            }else{
            	andView.setViewName(PAGE_500);
            }
        } else {
            andView.addObject("status", status.value());
            andView.setViewName(OTHER_ERROR);
        }
        return andView;
	}
    
}